#include "addform.h"
#include "ui_addform.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>

AddForm::AddForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AddForm)
{
    ui->setupUi(this);
}

AddForm::~AddForm()
{
    delete ui;
}

void AddForm::on_pushButton_clicked()
{
    // 1. 收集表单数据
    QString name = ui->nameLine->text();
    QString nickname = ui->nickLine->text();
    QString gender = ui->genderLine->text();
    QString age = ui->ageLine->text();
    QString dept = ui->deptLine->text();

    // 2. 发送请求，并将收集到数据一起发送给服务器端
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    QNetworkRequest request;
    // 重设请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    // 设置请求地址
    request.setUrl(QUrl("http://127.0.0.1:8088/school/api/v1.0/student"));
    // 设置发送到服务器端的数据
    QString params = QString("sname=%1&snickname=%2&sgender=%3&sage=%4&sdept=%5").arg(name).arg(nickname).arg(gender).arg(age).arg(dept);
    // 采用post方式发送请求
    manager->post(request, params.toUtf8());


    // 3. 处理服务器的响应
    connect(manager, &QNetworkAccessManager::finished, [this](QNetworkReply *reply){
        // qDebug() << reply->readAll();
        // this->close();
        emit this->reload();
    });
}
